import { Table, Checkbox, Input, Select } from 'antd'
import c from 'classnames'
import  defaultAvatar  from '@/desktop/assets/avatar.jpg'
import {
  type ChoosingData,
  type AccountForChoose,
  type QywxForChoose,
  useChoosingData,
  useChoose,
} from './hooks'
import './index.less'

export type { QywxForChoose, AccountForChoose, ChoosingData }

const prefix = 'qun-choose-qywxs'
const pfx = (className?: string) =>
  typeof className === 'string' ? `${prefix}-${className}` : prefix

export default function ChooseQywx<Q extends QywxForChoose = QywxForChoose>(props: {
  data?: ChoosingData<Q> // 自行提供待选择数据（不提供则组件自动拉取数据）
  onlineOnly?: boolean // 组件拉取数据时，是否只拉取在线的企业微信（默认 true）
  disabledWxids?: Set<string> // 不允许选中的 wxid 列表
  choosed: string[] // 当前选中的 wxid 列表
  setChoosed: (wxids: string[]) => void // 更新选中列表
  className?: string
  qywxExtra?: (qywx: Q) => JSX.Element // 渲染各企业微信额外显示的信息
}) {
  const {
    data: inputData,
    onlineOnly,
    choosed,
    setChoosed,
    disabledWxids,
    className,
    qywxExtra,
  } = props
  const { conditions, updateConditions, accounts, qywxs, filteredQywxs } = useChoosingData<Q>(
    inputData ? { inputData } : { onlineOnly },
  )
  const { switchChoose } = useChoose({ qywxs, disabledWxids, choosed, setChoosed })

  const isDisabled = useCallback(
    (wxid: string) => disabledWxids?.has(wxid) === true,
    [disabledWxids],
  )

  // ===================================

  const getRowEvents = useCallback(
    ({ wxid }: Q) => ({
      onClick() {
        if (!isDisabled(wxid)) switchChoose(wxid)
      },
    }),
    [switchChoose, isDisabled],
  )

  const renderChoose = useCallback(
    ({ wxid }: Q) => <Checkbox checked={choosed.includes(wxid)} disabled={isDisabled(wxid)} />,
    [choosed, isDisabled],
  )

  const renderQywx = useCallback(
    (qywx: Q) => <QywxCell qywx={qywx} extra={qywxExtra} disabled={isDisabled(qywx.wxid)} />,
    [qywxExtra, isDisabled],
  )
  const renderAccount = useCallback(
    (qywx: Q) => <AccountCell accounts={accounts} qywx={qywx} disabled={isDisabled(qywx.wxid)} />,
    [accounts, isDisabled],
  )

  return <div className={c(pfx(), className)}>
    <div className={pfx('search')}>
      <label>
        <span>企微账号：</span>
        <Input
          placeholder="输入关键词进行搜索"
          value={conditions.keyword}
          onChange={e => updateConditions({ keyword: e.target.value })}
        />
      </label>
      <label>
        <span>所属员工：</span>
        <Select
          value={conditions.accountId}
          onChange={accountId => updateConditions({ accountId })}
        >
          <Select.Option value="">请选择</Select.Option>
          {(accounts ?? []).map(account => <Select.Option key={account.id} value={account.id}>
            {account.name}
            {account.remark ? <span className={pfx('remark')}>（{account.remark}）</span> : null}
          </Select.Option>)}
        </Select>
      </label>
    </div>

    <div className={pfx('qywxs')}>
      <Table<Q>
        rowKey="wxid"
        dataSource={filteredQywxs}
        scroll={{ y: 500 }}
        pagination={false}
        onRow={getRowEvents}
      >
        <Table.Column<QywxForChoose> title="" width={70} align="center" render={renderChoose} />
        <Table.Column<QywxForChoose> title="企微账号" render={renderQywx} />
        <Table.Column<QywxForChoose> title="所属员工" width={200} render={renderAccount} />
      </Table>
    </div>
  </div>
}

function QywxCell<Q extends QywxForChoose = QywxForChoose>(props: {
  qywx: Q
  disabled: boolean
  extra?: (qywx: Q) => JSX.Element
}) {
  const { qywx, disabled, extra } = props
  return <div className={c(pfx('qywx-info'), disabled && pfx('disabled'))}>
    <img src={qywx.avatar || defaultAvatar} />
    <div className={pfx('info-main')}>
      <div className={pfx('name')}>{qywx.friendlyName}</div>
      <div className={pfx('corp')}>{qywx.corpname}</div>
    </div>
    {extra ? extra(qywx) : null}
  </div>
}

function AccountCell(props: {
  accounts?: AccountForChoose[]
  qywx: QywxForChoose
  disabled: boolean
}) {
  const { accounts, qywx, disabled } = props
  const account = accounts?.find(v => v.id === qywx.accountId)
  if (!account) return null
  return <div className={c(pfx('account'), disabled && pfx('disabled'))}>
    {account.name}
    {account.remark ? <span className={pfx('remark')}>（{account.remark}）</span> : null}
  </div>
}
